package com.xfreelance.qcshop.controller;

import cn.hutool.core.date.DateUtil;
import com.xfreelance.qcshop.commom.RestBody;
import com.xfreelance.qcshop.entity.User;
import com.xfreelance.qcshop.service.UserService;
import com.xfreelance.qcshop.utils.WxUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class WxAuthController {

    @Autowired
    private WxUtil wxUtil;
    @Autowired
    private UserService userService;

    @PostMapping("/gettoken")
    public RestBody getToken(@RequestParam String code) {
        String openId = wxUtil.getOpenId(code);
        User user = userService.findByOpenId(openId);
        if (user == null) {
            user = new User();
            user.setWxOpenId(openId);
            userService.add(user);
        } else {
            user.setLastLoginTime(DateUtil.date().toTimestamp());
            userService.update(user);
        }
        Map<String, String> data = new HashMap<>();
        data.put("token", openId);
        return RestBody.success(data);
    }
}
